package com.chihb.service.impl;

import com.chihb.domain.LoginUser;
import com.chihb.domain.User;
import com.chihb.service.UserService;
import com.chihb.util.JwtUtil;
import com.chihb.util.RedisCache;
import com.chihb.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

import static com.chihb.util.LoginEnum.LOGIN_OUT;
import static com.chihb.util.LoginEnum.LOGIN_SUCCESS;
import static com.chihb.util.constant.USER_LOGIN_STATE;
import static com.chihb.util.constant.USER_LOGIN_TOKEN;

/**
 * @author chihb
 * @create-time 2024/11/29 11:07
 * @description
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Override
    public Result login(User user) {
        // 获取用户名和密码组成认证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        // 调用AuthenticationManager的authenticate进行身份认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没有通过，抛出异常
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        // 认证通过，使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        // 把完整的用户信息存入redis，userid作为key【为避免重复，可以添加一些前缀】
        redisCache.setCacheObject(USER_LOGIN_STATE+userId,loginUser);

        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put(USER_LOGIN_TOKEN,jwt);
        return new Result(LOGIN_SUCCESS.getCode(),LOGIN_SUCCESS.getMsg(),map);

    }

    @Override
    public Result logout() {
        // 获取SecurityContextHolder中的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();

        // 删除redis里面的值
        redisCache.deleteObject(USER_LOGIN_STATE + userid);
        return new Result(LOGIN_OUT.getCode(), LOGIN_OUT.getMsg());
    }
}
